﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web.Mvc;
using Kaiser.Extensions;
using Kaiser.Infrastructure.Controllers;
using Kaiser.Models;
using Kaiser.Models.InputModels;
using Kaiser.Models.JsonModels;
using Kaiser.Models.SearchModels;
using Kaiser.Services;
using Kaiser.Utilities;
using Kaiser.Utilities.Ueditor;

namespace Kaiser.Modules.Admin.Controllers
{
    public class AttachManageController : KaiserBaseController
    {
        private IAttachService _attachService;

        private KaiserBaseControllerHelp<Attach> _help;

        public AttachManageController(IAttachService attachService)
        {
            _attachService = attachService;
            _help = new KaiserBaseControllerHelp<Attach>(this, attachService);
        }

        public ActionResult AttachList()
        {
            return View();
        }


        [HttpPost]
        public ActionResult AttachList(AttachSearch search, PagingInfo pageinfo, FormCollection form)
        {
            var result = _attachService.SearchAttach(search, pageinfo);
            return Content(result.ToJsonString());
        }



        public ActionResult AddAttach(string parentId, string parentName)
        {
            var model = new Attach();

            return View("EditAttach", model);

        }

        public ActionResult EditAttach(string id)
        {
            return _help.GetModel(id);
        }

        [HttpPost]
        public ActionResult AddAttach(Attach model, FormCollection form)
        {
            model.Attach_CreateUserName = CurrentUser.Name;
            // model. = CurrentUser.DisplayName;
            model.Attach_CreateTime = DateTime.Now;
            // model.ParentId = string.IsNullOrEmpty(model.ParentId) ? "0" : model.ParentId;
            return _help.AddModel(model);
        }

        [HttpPost]
        public ActionResult EditAttach(Attach model, FormCollection form)
        {

            return _help.EditModel(model.Attach_ID, model, form);
        }

        private void SaveAttach(Attach attach)
        {

        }



        [HttpPost]
        public void DownFile(string id)
        {
            var attach = FactoryBuider.CreateAttachService().Get(id);
            FileDown.DownLoadold(attach.Attach_Path);
        }

        [HttpPost]
        public ActionResult UploadFile()
        {
            var context = System.Web.HttpContext.Current;
            context.Response.ContentType = "text/plain";

            //上传配置
            String pathbase = "upload/";                                      //保存路径
            string[] filetype = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv" };    //文件允许格式
            int size = 100;   //文件大小限制,单位MB,同时在web.config里配置环境默认为100MB


            //上传文件
            Hashtable info = new Hashtable();
            Uploader up = new Uploader();
            info = up.upFile(context, pathbase, filetype, size); //获取上传状态

            //context.Response.Write("{'state':'" + info["state"] + "','url':'" + info["url"] + "','fileType':'" + info["currentType"] + "','original':'" + info["originalName"] + "'}"); //
            return Json(new
                 {
                     state = info["state"],
                     url = info["url"],
                     fileType = info["currentType"],
                     original = info["originalName"]
                 });
        }

   
        public ActionResult UploadImage()
        {
            var context = System.Web.HttpContext.Current;
            //上传配置
            int size = 2;           //文件大小限制,单位MB                             //文件大小限制，单位MB
            string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };         //文件允许格式


            //上传图片
            Hashtable info = new Hashtable();
            Uploader up = new Uploader();

            string pathbase = null;
            int path = Convert.ToInt32(up.getOtherInfo(context, "dir"));
            if (path == 1)
            {
                pathbase = "/UploadFile/NewsPic/";

            }
            else
            {
                pathbase = "/UploadFile/NewsPic/";
            }

            info = up.upFile(context, pathbase, filetype, size);                   //获取上传状态

            string title = up.getOtherInfo(context, "pictitle");                   //获取图片描述
            string oriName = up.getOtherInfo(context, "fileName");                //获取原始文件名
            return Json(new { url = info["url"], title = title, original = oriName, state = info["state"] });
        }

        [HttpPost]
        public ActionResult UploadFiles(AttachUpLoad attach)
        {
            JsonReturnMessages result = new JsonReturnMessages();
            //context.Response.ContentType = "text/html";

            try
            {
                if (Request.Files.Count > 0)
                {

                    string savePath = string.Format(@"/UploadFile/{0}/{1}/", attach.ObjectModule ?? "Temp", DateTime.Now.ToString("yyyy-MM-dd"));

                    //string filePath = path + @"\" + Guid.NewGuid().GenerateGuid().ToString();
                    var file = Request.Files[0];
                    //获取用户上传文件的后缀名
                    if (file != null)
                    {
                        string extension = Path.GetExtension(file.FileName);

                        var upload = new ImageUpload();
                        upload.SavePath = savePath;
                        upload.FormFile = file;
                        upload.InFileName = Guid.NewGuid().GenerateGuid().ToString() + extension;
                        upload.SaveType = 1;
                        upload.Upload();


                        Attach model = new Attach();
                        model.Attach_ContentType = file.ContentType;
                        model.Attach_CreateTime = DateTime.Now;
                        model.Attach_FileName = file.FileName;
                        model.Attach_ObjectID = attach.ObjectID;
                        model.Attach_ObjectModule = attach.ObjectModule;
                        model.Attach_Path = upload.SaveUrl;
                        model.Attach_Size = file.ContentLength;

                        _help.Service.Insert(model);
                        result.Data = new
                            {
                                FilePath = model.Attach_Path,
                                FileName = model.Attach_FileName,
                                Id = model.Attach_ID.ToString()
                            };
                    }

                }
                else
                {
                    throw new Exception("@上传文件不能为空！");

                }
            }
            catch (Exception ex)
            {
                result.success = false;
                result.msg = ex.Message;
            }

            return Json(result);
        }


        public ActionResult DelAttachDetail(IList<string> ids)
        {
            return _help.DelModel(ids);
        }

    }
}
